package com.sdwz.borrow.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdwz.borrow.client.LibraryClient;
import com.sdwz.borrow.client.UserClient;
import com.sdwz.borrow.entity.BookInfo;
import com.sdwz.borrow.entity.BorrowInfo;
import com.sdwz.borrow.entity.PenaltyInfo;
import com.sdwz.borrow.entity.vo.PenaltyDetail;
import com.sdwz.borrow.service.BorrowInfoService;
import com.sdwz.borrow.service.PenaltyInfoService;
import com.sdwz.commonutil.Result;
import com.sdwz.serviceutil.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 罚款信息表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-03-30
 */
@RestController
@RequestMapping("/api/borrow")
public class PenaltyInfoController {

    @Autowired
    PenaltyInfoService penaltyInfoService;

    @Autowired
    BorrowInfoService borrowInfoService;

    @Autowired
    LibraryClient libraryClient;

    @Autowired
    UserClient userClient;

    /**
     * 罚款信息
     * @param request
     * @return
     */
    @GetMapping("/auth/penalty/info")
    public Result getTimeOutInfo(HttpServletRequest request){
        String userId = String.valueOf(JwtUtil.getUserId(request.getHeader("token")));
        QueryWrapper<PenaltyInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("penalty_status",0);
        List<PenaltyInfo> penaltyInfos = penaltyInfoService.list(wrapper);

        List<PenaltyDetail> penaltyDetails = new ArrayList<>();
        //1获取超时借阅信息

        BigDecimal amount = new BigDecimal(0);

        List<String> penaltyIds = new ArrayList<>();

        //获取每本超时书籍的信息和对应的罚款
        for (PenaltyInfo penaltyInfo:penaltyInfos){
            PenaltyDetail penaltyDetail = new PenaltyDetail();
            penaltyDetail.setPenaltyId(penaltyInfo.getId());
            penaltyDetail.setUserId(userId);
            penaltyDetail.setBookId(penaltyInfo.getBookId());
            penaltyDetail.setSubject(penaltyInfo.getSubject());
            penaltyDetail.setReturnTime(penaltyInfo.getCreateTime());
            //获取书籍金额
            BookInfo book = libraryClient.getBook(penaltyInfo.getBookId());
            penaltyDetail.setBookName(book.getBookName());
            penaltyDetail.setPrice(book.getPrice());
            penaltyDetail.setSingleAmount(penaltyInfo.getAmount());
            amount = amount.add(penaltyInfo.getAmount());
            penaltyDetails.add(penaltyDetail);
            penaltyIds.add(penaltyInfo.getId());
        }

        Map<String,Object> result = new HashMap<>();
        result.put("allAmount",amount);
        result.put("penaltyDetails",penaltyDetails);
        result.put("penaltyIds",penaltyIds);

        return Result.ok(result);

    }

    /**
     * 支付罚款信息
     * @param request
     * @return
     */
    @PostMapping("/auth/penalty/pay")
    public Result handleTimeOut(HttpServletRequest request,
                                @RequestBody List<String> penaltyIds){
        String userId = String.valueOf(JwtUtil.getUserId(request.getHeader("token")));

        List<PenaltyInfo> penaltyInfos = penaltyInfoService.listByIds(penaltyIds);
        List<BorrowInfo> borrowInfos = new ArrayList<>();
        for (PenaltyInfo penaltyInfo:penaltyInfos){
            BorrowInfo borrowInfo = new BorrowInfo();
            borrowInfo.setId(penaltyInfo.getBorrowId());
            borrowInfo.setStatus(0);
            borrowInfos.add(borrowInfo);
            penaltyInfo.setPenaltyStatus(1);
        }
        penaltyInfoService.saveOrUpdateBatch(penaltyInfos);
        borrowInfoService.saveOrUpdateBatch(borrowInfos);

        return Result.ok();

    }

    /**
     * 根据天数计算罚款
     * @param day
     * @param price
     * @return
     */
    private BigDecimal calculateAmount(int day,BigDecimal price){
        BigDecimal money = new BigDecimal(0);
        if (day<=10){
            money = money.add(price.multiply(new BigDecimal("0.05")).multiply(new BigDecimal(day)));
        }
        if (day >10 && day<=15){
            money = money.multiply(new BigDecimal("0.05")).multiply(new BigDecimal(5)).add(money.multiply(new BigDecimal("0.1")).multiply(new BigDecimal(day-5)));
        }
        if (day>15){
            money = price.multiply(new BigDecimal(2));
        }
        return money;
    }

    /**
     * 获取超期天数
     * @param startDay
     * @param endDay
     * @return
     */
    public int calculateDay(Date startDay,Date endDay){
        int i=0;

        Date nextDay=startDay;

        while(nextDay.before(endDay)){//当明天不在结束时间之前是终止循环
            Calendar cld = Calendar.getInstance();
            cld.setTime(startDay);
            cld.add(Calendar.DATE, 1);
            startDay = cld.getTime();
            //获得下一天日期字符串
            nextDay = startDay;
            i++;
        }
        return i;
    }
}

